package ${cfg.package_name}.controller;

//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.DateTool;
import com.rt.easyjava.common.base.MyQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.rt.easyjava.common.base.UserDetailsDto;
import com.rt.easyjava.common.base.PageDto;
import ${cfg.package_name}.dto.${entity}Dto;
import ${cfg.package_name}.bean.${entity};
import ${cfg.package_name}.service.${entity}Service;
import ${cfg.package_name}.dtomapper.${entity}DtoMapper;
import java.util.List;
import javax.annotation.Resource;

/**
* ${table.comment!}前端控制器
* 1，用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，userDetailsJson)
* @author ${author}
* @since ${date}
*/
@Slf4j
//@Api(tags = "${table.entityName}Controller - ${table.comment} 控制类")
@RequestMapping("/${cfg.module}/${cfg.domain}/${table.entityPath}/")
@Controller
public class ${table.entityName}Controller {
    @Autowired
    protected ${entity}Service ${table.entityPath}Service;
    @Resource
    private ${entity}DtoMapper ${table.entityPath}DtoMapper;


    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:query')")
    //@ApiOperation("自定义sql分页查询（mapper.xml, 适合多表查询）")
    @GetMapping(value = "/myPage")
    @ResponseBody
    public Result myPage(@ModelAttribute ${table.entityName}Dto ${table.entityPath}Dto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "${cfg.module}:${table.entityPath}:query");
        Page<${table.entityName}> page = new Page<>(${table.entityPath}Dto.getPage(), ${table.entityPath}Dto.getLimit());

        // 查询条件
        ${table.entityName} ${table.entityPath}Query = ${table.entityPath}DtoMapper.dto2bean(${table.entityPath}Dto);

        // set deleteflag default 0, 查询参数时，默认只查有效数据
        ${table.entityPath}Query.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        ${table.entityPath}Query.rebuildDataLimitQueryBean(userDetailsDto);

        // 查询
        QueryWrapper<${table.entityName}> queryWrapper=new QueryWrapper<>(${table.entityPath}Query);
        // queryWrapper.orderBy(${table.entityPath}Dto.getCondition(), ${table.entityPath}Dto.isAsc(), "t1."+${table.entityPath}Dto.getColumn());
        // 支持前端：listQuery.sort='-part_no,-id'
        for (PageDto sortDto:${table.entityPath}Dto.getSortList()){
            queryWrapper.orderBy(true, sortDto.getAsc(), "t1."+sortDto.getColumn());
        }

        return ${table.entityPath}Service.myPage(page, queryWrapper, ${table.entityPath}Dto.getHasFooter());
    }


    /**
        树结构查询方法，非树结构会造一个空方法备用着。
    @PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:query')")
    @ApiOperation("以ID作为父节点，查询子树")
    @GetMapping(value = "/tree")
    @ResponseBody
    public Result tree (Long id) {
        Result<${entity}Dto> result = new Result<>();
        // when id=0 , id=0 is parantId=0 , 默认设置一个空根
        ${entity}Dto ${table.entityPath}Dto = new ${entity}Dto();
        <#if cfg.idType?? && cfg.idType=='uuid'>
        ${table.entityPath}Dto.setId("0");
        <#else >
        ${table.entityPath}Dto.setId(0L);
        </#if>
        if (id!=0) {
            ${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);
            ${table.entityPath}Dto = mapper.map(${table.entityPath}, ${entity}Dto.class);
        }
        treeReduce(${table.entityPath}Dto);
        result.setObj(${table.entityPath}Dto);

        return result.success();
    }

    private void treeReduce(${entity}Dto ${table.entityPath}Dto){
        <#if cfg.isTreeTable == true>
        // myson list
        QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
        // queryWrapper.eq("${cfg.tableNameFirstWordLower}_id", ${table.entityPath}Dto.getId());
        queryWrapper.eq("parent_id", ${table.entityPath}Dto.getId());
        queryWrapper.eq("deleteflag", 0);
        queryWrapper.orderByAsc(true, "id");
        List<${entity}> sonList = ${table.entityPath}Service.list(queryWrapper);
        if (sonList.size() == 0) {
            return;
        }
        List<${entity}Dto> sonDtoList = mapper.maplist(sonList, ${entity}Dto.class);

        ${table.entityPath}Dto.set${entity}List(sonDtoList);
        for (${entity}Dto dto : sonDtoList) {
            treeReduce(dto);
        }
        </#if>
    }
    */


    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:query')")
    //@ApiOperation("查询所有")
    @GetMapping(value = "/selectBy")
    @ResponseBody
    public Result selectBy(@ModelAttribute ${table.entityName}Dto ${table.entityPath}Dto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "${table.entityPath}:query");
        Result<${table.entityName}Dto> result = new Result<>();

        // 查询条件
        ${table.entityName} ${table.entityPath}Query = ${table.entityPath}DtoMapper.dto2bean(${table.entityPath}Dto);

        // set deleteflag default 0, 查询参数时，默认只查有效数据
        ${table.entityPath}Query.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        ${table.entityPath}Query.rebuildDataLimitQueryBean(userDetailsDto);

        QueryWrapper<${table.entityName}> queryWrapper=new QueryWrapper<>(${table.entityPath}Query);
        queryWrapper.orderBy(${table.entityPath}Dto.getCondition(), ${table.entityPath}Dto.isAsc(), ${table.entityPath}Dto.getColumn());

        result = ${table.entityPath}Service.selectBy(queryWrapper);

        return result;
    }

    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:query')")
    //@ApiOperation("selectById")
    @GetMapping(value = "/selectById")
    @ResponseBody
    public Result selectById(Long id){
        return ${table.entityPath}Service.selectById(id);
    }

    /*
    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:query')")
    //@ApiOperation("SQL动态多选项, spring动态调用")
    @GetMapping(value = "/select4column")
    @ResponseBody
    public Result select4column(String columnName){
        return ${table.entityPath}Service.select4column(columnName);
    }
    */

    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:create')")
    //@ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    public Result create(@RequestBody ${table.entityName}Dto ${table.entityPath}Dto, String userDetailsJson){
        //插入参数
        //${table.entityPath}Dto.setCreatorUpdatorInfo(userDetailsJson);

        //调用服务
        return ${table.entityPath}Service.create(${table.entityPath}Dto);
    }

    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:update')")
    //@ApiOperation("编辑对象")
    @PostMapping(value = "/update")
    @ResponseBody
    public Result update(@RequestBody ${table.entityName}Dto ${table.entityPath}Dto, String userDetailsJson){
        try{
            ${table.entityPath}Dto.getId().longValue();
        }catch (Exception e){
            return Result.builder().fault("数据中缺少ID");
        }

        //参数
        //${table.entityPath}Dto.setUpdatorInfo(userDetailsJson);

        //调用服务
        return ${table.entityPath}Service.updateByDtoId(${table.entityPath}Dto);
    }

    //@PreAuthorize("hasAuthority('${cfg.module}:${table.entityPath}:delete')")
    //@ApiOperation("逻辑删除对象，由deleteflag控制：0:有效，1:已删除。")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(Long id, String userDetailsJson){
        try{
            id.longValue();
        }catch (Exception e){
            return Result.builder().fault("数据中缺少ID");
        }
        //参数
        ${table.entityName}Dto ${table.entityPath}Dto = new ${table.entityName}Dto();
        ${table.entityPath}Dto.setId(id);
        //${table.entityPath}Dto.setUpdatorInfo(userDetailsJson);
        ${table.entityPath}Dto.setDeleteFlag(1);

        <#--//query condition for update
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", id==null?0:id.longValue());-->
        //调用服务
        return ${table.entityPath}Service.updateByDtoId(${table.entityPath}Dto);
    }


}
